package com.woniuxy.factory.service.imp;

import com.woniuxy.factory.entity.EmpUser;
import com.woniuxy.factory.entity.ResponseResult;
import com.woniuxy.factory.exception.BusinessException;
import com.woniuxy.factory.mapper.EmpUserMapper;
import com.woniuxy.factory.service.EmpUserService;
import com.woniuxy.factory.util.AuditType;
import com.woniuxy.factory.util.MD5_Encoding;
import com.woniuxy.factory.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Service
public class EmpUserServiceImp implements EmpUserService {
    @Autowired
    EmpUserMapper empUserMapper;
    //登录
    @Override
    public ResponseResult login(EmpUser empUser, HttpServletRequest request) {
        empUser.setPassWord(MD5_Encoding.upperMD5(empUser.getPassWord()));
        EmpUser empUser1 = empUserMapper.selectEmpUser(empUser);
        if (empUser1==null){
            throw new BusinessException("账号或密码错误，登录失败");
        }
        HttpSession session = request.getSession();
        session.setAttribute("account",empUser1);
        return new ResponseResult(AuditType.No_Approval,"登录成功",null,null);
    }
    //注册
    @Override
    public ResponseResult register(EmpUser empUser, String empId) {
        empUser.setPassWord(MD5_Encoding.upperMD5(empUser.getPassWord()));
        empUser.setCreateTime(new Date());
        empUser.setUseId(UuidUtil.get16UUID());
        int i = empUserMapper.insertEmpUser(empUser,empId);
        if(i==0){
            throw new BusinessException("注册失败");
        }
        return new ResponseResult(AuditType.No_Approval,"注册成功",null,null);
    }

    @Override
    public ResponseResult exitUser(HttpServletRequest request) {
        Object account = request.getSession().getAttribute("account");
        if (account==null){
            return new ResponseResult(AuditType.ALREADY_PASSED,"当前状态异常",null,null);
        }
        try {
            request.getSession().removeAttribute("account");
            return new ResponseResult(AuditType.No_Approval,"退出成功",null,null);
        }catch (RuntimeException e){
            return new ResponseResult(AuditType.ALREADY_PASSED,"系统异常，请联系管理员",null,null);
        }

    }
}
